package utils

import "strings"

const (
	CHARS      = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
	SCALE      = 62
	MIN_LENGTH = 6
)

// Encode62 将 long 转为 Base62 编码，并左补零到 MIN_LENGTH
func Encode62(num int64) string {
	if num == 0 {
		return strings.Repeat("0", MIN_LENGTH)
	}

	var sb strings.Builder
	for num > 0 {
		remainder := num % SCALE
		sb.WriteByte(CHARS[remainder])
		num /= SCALE
	}

	// 反转字符串
	encoded := reverse(sb.String())

	// 左补零
	if len(encoded) < MIN_LENGTH {
		encoded = strings.Repeat("0", MIN_LENGTH-len(encoded)) + encoded
	}

	return encoded
}

func reverse(s string) string {
	runes := []rune(s)
	for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {
		runes[i], runes[j] = runes[j], runes[i]
	}
	return string(runes)
}
